﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyMainSite.Models;

namespace MyMainSite.Repositories
{
	public class ProjectBuildRepository
	{
		#region Public Methods

		public int AddBuild(int projectId, string name, string fileName, int size, byte[] data, Version version)
		{
			if (String.IsNullOrWhiteSpace(name))
				throw new ArgumentException("name");
			if (String.IsNullOrWhiteSpace(fileName))
				throw new ArgumentException("fileName");

			RichardsSiteEntities context = new RichardsSiteEntities();

			ProjectRepositoryImplemented projectRepo = new ProjectRepositoryImplemented();
			if (projectRepo.GetProjectById(projectId) == null)
				throw new ArgumentException(String.Format("Invalid Project Id: {0}", projectId));

			ProjectBuild build = new ProjectBuild();
			build.ProjectId = projectId;
			build.Name = name;
			build.FileName = fileName;
			build.Size = size;
			build.Data = data;
			build.UploadDate = DateTime.Now;
			build.Version = version.ToString();

			try
			{
				context.ProjectBuilds.AddObject(build);
				context.SaveChanges();
			}
			catch (Exception ex)
			{
				// TODO: implement logging into DotNetX
				return 0;
			}

			return build.ProjectId;
		}

		public bool IsProjectBuildNameAndVersionUnique(string name, Version version)
		{
			if (String.IsNullOrWhiteSpace(name))
				throw new ArgumentException("name");

			RichardsSiteEntities context = new RichardsSiteEntities();

			string v = version.ToString();

			var build = (from b in context.ProjectBuilds
						 orderby b.Name ascending
						 where b.Name.Trim().ToLower() == name &&
							   b.Version.Trim().ToLower() == v
						 select b).SingleOrDefault();

			return build == null;
		}

		#endregion
	}
}